<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { h, onMounted, ref, watch } from 'vue'
  import DateRange from '@/components/business/date-range/DateRange.vue'
  import fixedData from '@/config/fixed-data/warehouse/out-store'
  import { useRoute, useRouter } from 'vue-router'
  import routeComponentName from '@/config/route-component-name'
  import { ElDivider, TableInstance, ElMessage } from 'element-plus'
  import { useGetAllWarehouseOptionList } from '@/services/pages/storage/useWarehouse'
  import _ from 'lodash'
  import { useGetAllotInWarehouseList } from '@/services/pages/storage/useWarehouse'
  import SignModal from '@/components/pages/Warehouse/allot/sign-modal.vue'
  import { HMessageBox } from '@/components/common/message'
  import { getTransferInStoreExcelExport } from '@/api/store'
  import moment from 'moment'

  const {
    optionList: warehouseOptionList,
    getOptionListParam: getWarehouseOptionListParam,
    getOptionListLoading: getWarehouseOptionListLoading,
    getOptionList: getWarehouseOptionList,
  } = useGetAllWarehouseOptionList()
  const { list, listTotal, getListParam, getListLoading, getList } = useGetAllotInWarehouseList()

  defineOptions({
    name: routeComponentName.storage.warehouseAllotIn,
  })

  // 签收弹窗显示状态
  const signModalVisible = ref(false)

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 激活路由对象
  const route = useRoute()

  // 选择的出库列表
  const selectionList = ref<Array<WarehouseOut>>([])

  // 全局路由对象
  const router = useRouter()

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 日期类型
  const dateTypeList = [
    { title: '今天', value: 2 },
    { title: '本周', value: 3 },
    { title: '本月', value: 4 },
    { title: '自定义时间', value: 1 },
  ]

  // 单据来源
  const sourceList = [
    { title: '系统单', value: 1 },
    { title: '工单', value: 2 },
    { title: 'ERP单据', value: 3 },
    // { title: '仓库移动端单据', value: 4 },
    // { title: '第三方系统单据', value: 5 },
    // { title: '用友', value: 6 },
    { title: '部门移动端单据', value: 7 },
  ]

  // 出库单状态
  const statusList = [
    { title: '待审核', value: 1 },
    { title: '待入库', value: 2 },
    { title: '驳回', value: 3 },
    { title: '已入库', value: 4 },
    { title: '已作废', value: 5 },
    { title: '待签收', value: 6 },
    { title: '未提交', value: 50 },
  ]

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 选中的状态
  const activeStatus = ref<1 | 2 | 3 | 4 | 5 | 6 | 7 | ''>('')

  /**
   * 获取列表
   */
  const _getList = () => {
    if (paginationInstance.value) {
      getListParam.value.type = 0
      getListParam.value.limit = paginationInstance.value.size
      getListParam.value.page = paginationInstance.value.current
      if (getListParam.value.limit >= listTotal.value) {
        getListParam.value.page = 1
      }
      getList()
    }
  }

  /**
   * 日期类型更新事件
   */
  const onDateTypeChange = () => {
    if (getListParam.value.dateType !== 1) {
      _getList()
    }
  }

  /**
   * 详情点击事件
   * @param {WarehouseOut} warehouseOut - 出库对象
   */
  const handleDetailClick = (warehouseOut: WarehouseOut) => {
    if ([1, 3].includes(warehouseOut.status)) {
      router.push({
        path: `/storage/allot/in/create/${warehouseOut.id}/${warehouseOut.status}`,
      })
    } else {
      router.push(`/storage/allot/in/detail/${warehouseOut.id}`)
    }
  }

  /**
   * 表格选择事件
   * @param {Array<WarehouseOut>} list - 选择的列表
   */
  const handleTableSelection = (list: Array<WarehouseOut>) => {
    selectionList.value = list
  }

  /**
   * 新增出库点击事件
   */
  const handleCreateWarehouseOut = () => {
    router.push({
      path: '/storage/allot/in/create',
      query: { documentSourceId: fixedData.material_apply_id },
    })
  }

  /**
   * 重置点击事件
   */
  const onReset = () => {
    Object.assign(getListParam.value, {
      dateType: '',
      endTime: '',
      search: '',
      source: '',
      startTime: '',
      status: '',
      typeId: '',
      storeIds: [],
      receiptStoreIds: [],
      submitType: '',
    })
    _getList()
  }

  /**
   * 获取仓库下拉选项列表
   * @param {string} keyword - 搜索关键字
   */
  const handleGetWarehouseOptionList = _.debounce((keyword: string) => {
    if (getWarehouseOptionListParam.value.name !== keyword) {
      getWarehouseOptionListParam.value.name = keyword
      getWarehouseOptionList()
    }
  }, 600)

  /**
   * 签收点击事件
   * @param {AllotInWarehouse} allotInWarehouse - 需要签收的调拨入库单
   */
  const handleSignClick = (allotInWarehouse: AllotInWarehouse) => {
    if (tableInstance.value) {
      tableInstance.value.clearSelection()
      tableInstance.value.toggleRowSelection(allotInWarehouse)
    }
    signModalVisible.value = true
  }

  /**
   * 批量签收点击事件
   */
  const onMultipleSignClick = () => {
    for (let i = 0; i < selectionList.value.length; i++) {
      if (selectionList.value[i].status !== 6) {
        HMessageBox.error('只能选择待签收的调拨入库单')
        return
      }
    }

    signModalVisible.value = true
  }

  // 导出
  const exportLoading = ref(false)
  const onExportClick = () => {
    exportLoading.value = true
    getTransferInStoreExcelExport(getListParam.value).then((res) => {
      exportLoading.value = false
      // 因为前端把responseType: 'blob'放到请求头里，所以当后端响应JSON时也会把JSON转为blob
      // 所以需要将响应的数据转回JSON对象，如果转换成功就说明返回的是JSON，否则则是文件流
      const reader = new FileReader()
      reader.readAsText(res.data)
      reader.onload = function (result) {
        try {
          // 解析对象成功，说明后端返回的是JSON
          const resData = JSON.parse(result.target.result as string)
          ElMessage({
            showClose: true,
            message: resData.message,
            type: 'warning',
            offset: 200,
            plain: true,
          })
        } catch (err) {
          // 解析失败，说明后端返回的是文件流
          ElMessage({
            showClose: true,
            message: '调拨入库数据导出成功',
            type: 'success',
            offset: 200,
            plain: true,
          })
          const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
          const link = document.createElement('a')
          link.href = url
          link.download = `调拨入库_${moment(new Date()).format('YYYYMMDD')}.xlsx`
          link.click()
        }
      }
    })
  }

  /**
   * 状态更新事件
   */
  const handleStatusChange = () => {
    // getListParam.value.status = activeStatus.value
    // if (getListParam.value.status === 7) {
    //   getListParam.value.status = ''
    //   getListParam.value.submitType = 1
    // }
    _getList()
  }

  watch(
    () => route.name,
    (value) => {
      if (value === 'WarehouseAllotIn' && route.query.isUpdate === '1') {
        _getList()
      }
    },
  )

  onMounted(() => {
    _getList()
    getWarehouseOptionList()
  })
</script>

<template>
  <div class="material-apply-list">
    <div v-loading="getListLoading" class="container">
      <div class="header">
        <div class="btn-group">
          <h-plain-button @click="handleCreateWarehouseOut">新增调拨入库</h-plain-button>
          <h-plain-button :disabled="selectionList.length === 0" @click="onMultipleSignClick"
            >批量签收</h-plain-button
          >
          <h-plain-button v-loading="exportLoading" @click="onExportClick">导出</h-plain-button>
        </div>
        <div class="search">
          <el-select
            v-model="getListParam.dateType"
            class="date-type"
            placeholder="请选择日期类型"
            clearable
            @clear="_getList"
            @change="onDateTypeChange"
          >
            <el-option
              v-for="(dateType, dateTypeIndex) in dateTypeList"
              :key="dateTypeIndex"
              :value="dateType.value"
              :label="dateType.title"
            />
          </el-select>

          <DateRange
            v-if="getListParam.dateType === 1"
            ref="dateRangeRef"
            :start-date-width="140"
            :end-date-width="140"
          />

          <!-- 单据来源 -->
          <!-- <el-select
            v-model="getListParam.source"
            class="source"
            clearable
            placeholder="请选择单据来源"
            @clear="_getList"
            @change="_getList"
          >
            <el-option
              v-for="item in sourceList"
              :key="item.value"
              :value="item.value"
              :label="item.title"
            />
          </el-select> -->

          <!-- 调拨入库状态 -->
          <el-select
            v-model="getListParam.status"
            placeholder="请选择调拨入库状态"
            clearable
            class="status"
            @change="handleStatusChange"
            @clear="_getList"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :value="item.value"
              :label="item.title"
            />
          </el-select>

          <!-- 调入仓 -->
          <el-select
            v-model="getListParam.receiptStoreIds"
            placeholder="请选择调入仓"
            filterable
            clearable
            :filter-method="handleGetWarehouseOptionList"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            :loading="getWarehouseOptionListLoading"
            class="warehouse"
            @change="_getList"
            @clear="_getList"
          >
            <el-option
              v-for="(item, index) in warehouseOptionList"
              :key="index"
              :value="item.id"
              :disabled="item.disabled"
              :label="item.name"
            />
          </el-select>

          <!-- 调出仓 -->
          <el-select
            v-model="getListParam.storeIds"
            placeholder="请选择调出仓"
            filterable
            clearable
            :filter-method="handleGetWarehouseOptionList"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            :loading="getWarehouseOptionListLoading"
            class="warehouse"
            @change="_getList"
            @clear="_getList"
          >
            <el-option
              v-for="(item, index) in warehouseOptionList"
              :key="index"
              :value="item.id"
              :disabled="item.disabled"
              :label="item.name"
            />
          </el-select>

          <!-- 入库单号/收货人/手机号/制单人 -->
          <el-input
            v-model="getListParam.search"
            clearable
            placeholder="请输入库单号/收货人/手机号/制单人"
            class="input"
            @clear="_getList"
            @change="_getList"
          />

          <h-button type="primary" @click="_getList">
            <el-icon>
              <Search></Search>
            </el-icon>
            搜索
          </h-button>

          <h-button @click="onReset">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </h-button>
        </div>
      </div>
      <div class="main">
        <div class="table">
          <el-table
            ref="tableInstance"
            :border="true"
            :data="list"
            height="100%"
            @selection-change="handleTableSelection"
          >
            <!-- 多选 -->
            <el-table-column fixed="left" width="50" :align="'center'" type="selection" />

            <!-- 序号 -->
            <el-table-column label="序号" fixed="left" width="50" :align="'center'" type="index" />

            <!-- 制单时间 -->
            <el-table-column
              show-overflow-tooltip
              prop="createTime"
              fixed
              label="制单时间"
              width="128"
              :align="'center'"
            />

            <!-- 单号 -->
            <el-table-column
              show-overflow-tooltip
              prop="outboundNo"
              fixed
              label="单号"
              width="130"
              :align="'center'"
            >
              <template #default="{ row }">
                <HLink @click="handleDetailClick(row)">{{ row.outboundNo }}</HLink>
              </template>
            </el-table-column>

            <!-- 源单单号 -->
            <el-table-column
              show-overflow-tooltip
              prop="boundNo"
              fixed
              label="出库单号"
              width="128"
              :align="'center'"
            />

            <!-- 调入部门 -->
            <el-table-column label="调入部门" prop="network" width="140" :align="'center'" />

            <!-- 调出仓 -->
            <el-table-column show-overflow-tooltip label="调出仓" width="120" :align="'center'">
              <template #default="{ row }">{{ row.store.join('、') }}</template>
            </el-table-column>

            <!-- 调入仓 -->
            <el-table-column show-overflow-tooltip label="调入仓" width="120" :align="'center'">
              <template #default="{ row }">{{ row.inStore.join('、') }}</template>
            </el-table-column>

            <!-- 申请数量 -->
            <el-table-column
              show-overflow-tooltip
              label="申请数量"
              width="90"
              prop="applyQty"
              :align="'center'"
            />

            <!-- 实发数量 -->
            <el-table-column
              show-overflow-tooltip
              label="实发数量"
              width="90"
              prop="qty"
              :align="'center'"
            />

            <!-- 收货人 -->
            <el-table-column show-overflow-tooltip label="收货人" min-width="150" :align="'center'">
              <template #default="i"
                >{{ i.row.receiptName }}&nbsp;{{ i.row.receiptPhone }}</template
              >
            </el-table-column>

            <!-- 收货地址 -->
            <el-table-column label="收货地址" show-overflow-tooltip width="200">
              <template #default="{ row }">
                {{ row.receiptProvince }} {{ row.receiptCity }} {{ row.receiptArea }}
                {{ row.receiptAddress }}
              </template>
            </el-table-column>

            <!-- 制单人 -->
            <el-table-column
              show-overflow-tooltip
              prop="createEmp"
              label="制单人"
              width="80"
              :align="'center'"
            />

            <!-- 最后更新时间 -->
            <el-table-column
              show-overflow-tooltip
              prop="updateTime"
              label="最后更新时间"
              width="128"
              :align="'center'"
            />

            <!-- 反写状态 -->
            <el-table-column show-overflow-tooltip label="反写状态" width="120" :align="'center'">
              <template #default="{ row }">
                <h-status v-if="row.reverseWritingStatus === 1" type="error">反写失败</h-status>
                <h-status v-if="row.reverseWritingStatus === 2">反写成功</h-status>
              </template>
            </el-table-column>

            <!-- 反写失败原因 -->
            <el-table-column
              show-overflow-tooltip
              label="反写失败原因"
              width="120"
              :align="'center'"
            >
              <template #default="{ row }">
                {{ row.reverseWritingStatus === 1 ? row.reverseWritingFailReason : '' }}
              </template>
            </el-table-column>

            <!-- 调拨入库状态 -->
            <el-table-column
              prop="status"
              label="调拨入库状态"
              width="100"
              :align="'center'"
              fixed="right"
            >
              <template #default="{ row }">
                <div class="flex_justify_center">
                  <h-status v-if="row.submitType === 1">未提交</h-status>
                  <template v-else>
                    <HStatus v-if="row.status === 1" type="error">待审核</HStatus>
                    <HStatus v-if="row.status === 2" type="warning">待入库</HStatus>
                    <HStatus v-if="row.status === 3" type="info">已驳回</HStatus>
                    <HStatus v-if="row.status === 4" type="success">已入库</HStatus>
                    <HStatus v-if="row.status === 5" type="info">已作废</HStatus>
                    <HStatus v-if="row.status === 6" type="warning">待签收</HStatus>
                  </template>
                </div>
              </template>
            </el-table-column>

            <!-- 操作 -->
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-space :size="0" :spacer="spacer">
                  <h-link @click="handleDetailClick(row)">详情</h-link>
                  <h-link v-if="row.status === 6" @click="handleSignClick(row)">签收</h-link>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <pagination
            ref="paginationInstance"
            :list_total="listTotal"
            @size-change="_getList"
            @current-change="_getList"
          />
        </div>
      </div>
    </div>

    <!-- 签收弹窗 -->
    <sign-modal
      v-model="signModalVisible"
      :allot-in-warehouse-id-list="selectionList.map((item) => item.id)"
      @update="_getList"
    />
  </div>
</template>

<style scoped lang="scss">
  .material-apply-list {
    height: calc(100vh - 92px);
    width: 100%;
    padding: 12px;
    box-sizing: border-box;

    .container {
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      height: 100%;
      display: flex;
      flex-direction: column;
      row-gap: 12px;

      .header {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        row-gap: 5px;

        .btn-group {
          display: flex;
          column-gap: 5px;
        }

        .search {
          display: flex;
          column-gap: 5px;
          gap: 5px;
          flex-wrap: wrap;

          .date-type {
            width: 140px;
          }

          .source {
            width: 140px;
          }

          .status {
            width: 180px;
          }

          .input {
            width: 240px;
          }

          .warehouse {
            width: 160px;
          }
        }
      }

      .main {
        flex: 1;
        height: 0;
        display: flex;
        row-gap: 12px;
        flex-direction: column;

        .table {
          max-height: calc(100% - 40px);
        }

        .pagination {
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }
</style>
